﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using XCommunity.Web;
using XCommunity.Frames;
using System.Security;
using XCommunity.Documents;
using XCommunity;
using XCommunity.Users;

public partial class ModifyPost : System.Web.UI.Page
{

  protected Guid postId;
  protected GeneralTopicFrame topic;

  protected void Page_Load( object sender, EventArgs e )
  {


    AccountManage.RedirectLogin();
    //    if ( AccountContext.CurrentAccount == null )
    //      Response.Redirect( "Login.aspx", true );


    int topicId = int.Parse( Request.QueryString["topic"] );

    postId = new Guid( Request.QueryString["post"] );

    topic = (GeneralTopicFrame) WebCommunityContext.CurrentCommunityContext.FrameService.GetTopicFrame( topicId );

    var post = topic.GetPost( postId );

    if ( post.IsTheme )
      ModifyTopicTitlePlace.Visible = true;

    var permissions = ( (ICommunitySystem) WebCommunityContext.Current.ForumsSystem ).UserService.GetUserPermissions();

    if ( permissions.GetControl( "ModifyPost", post, topic ) != ControlType.Allow )
    {
      Response.Write( "您没有权限来执行这个操作！" );
      Response.End();
    }

    if ( permissions.GetControl( "ModifyTopicTitle", post, topic ) == ControlType.Allow )
      ModifyTopicTitle.Checked = true;


    if ( !IsPostBack )
    {
      TitleTextBox.Text = post.CurrentVersion.GetDocument().Meta.Caption;
      ContentTextBox.Text = ( (TextDocument) post.CurrentVersion.GetDocument() ).GetContent();
    }

  }


  protected void OnModifyPost( object sender, EventArgs e )
  {
    IHtmlDocumentProvider documentPlugin = WebCommunityContext.Current.GetDefaultDocumentProvider();

    Dictionary<string, string> meta = new Dictionary<string, string>() { { "Caption", TitleTextBox.Text } };
    Document document = documentPlugin.CreateDocument( ContentTextBox.Text, meta );

    ICommunityContext context = WebCommunityContext.CurrentCommunityContext;

    context.DocumentService.SaveDocument( document );


    topic.ModifyPost( postId, document );


    if ( topic.Theme.Guid == postId && ModifyTopicTitle.Checked )
    {
      topic.ModifyTitle( document.Meta.Caption );
    }




    Response.Redirect( Request.QueryString["source"] );

  }
}
